import * as vscode from 'vscode';
import * as path from 'path';
import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient/node';

let client: LanguageClient | undefined;

export async function startLspClient(context: vscode.ExtensionContext) {
    const cfg = vscode.workspace.getConfiguration('oh-yidian-tong');
    const enabled = cfg.get<boolean>('lsp.enabled');
    if (!enabled) return;

    const serverCommand = cfg.get<string>('lsp.serverCommand') || 'java';
    const serverArgs = cfg.get<string[]>('lsp.serverArgs') || [];

    const serverOptions: ServerOptions = {
        command: serverCommand,
        args: serverArgs,
        options: { cwd: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath }
    };

    const clientOptions: LanguageClientOptions = {
        documentSelector: [
            { scheme: 'file', language: 'cpp' },
            { scheme: 'file', language: 'c' },
            { scheme: 'file', language: 'gn' }
        ],
        synchronize: {
            fileEvents: vscode.workspace.createFileSystemWatcher('**/*.{cpp,c,h,gn}')
        }
    };

    client = new LanguageClient(
        'openharmonyLsp',
        'OpenHarmony Language Server',
        serverOptions,
        clientOptions
    );

    await client.start();
    context.subscriptions.push({ dispose: () => { if (client) { client.stop(); } } });
}

export async function stopLspClient() {
    if (client) {
        await client.stop();
        client = undefined;
    }
}


